<?php

namespace app\common\library;

use EasyWeChat\Factory;

/**
 * 微信公众号模块
 * https://easywechat.com/5.x/official-account/oauth.html
 * Class MyWeChat
 * @package wechat
 */
class MyWeChat
{
    const TEMPLATE_ID_ORDER_SUCCESS="JXjBCrG-OWojvbVFZgjftUXpatZj8V7L8Z-IJMSz04M";

    public $app;
    public function __construct()
    {
        $this->init();
    }

    protected function init()
    {
        $config = [
            'app_id' => "wxa68e4c5f67b33425",
            'secret' => "6ba771bf8dd20f76ab1d9456b25e1ee8",
            'oauth' => [
                'scopes'   => ['snsapi_userinfo'],
                'callback' => '/index/wxchat/auth_callback',
            ],

            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            //...
        ];
        $this->app = Factory::officialAccount($config);
    }

    /**
     * 发起授权
     */
    public function oauth_scopes()
    {
        $redirectUrl = $this->app->oauth->scopes(['snsapi_userinfo'])->redirect();
        header("Location: {$redirectUrl}");
    }

    /**
     * 获取已授权用户
     * @param $code
     * @return mixed
     */
    public function userFromCode($code)
    {
        return $this->app->oauth->userFromCode($code);
    }


    /**
     * 发送模版消息
     * @param $touser
     * @param $url
     * @param $template_id
     * @param $data
     */
    public function sendTemplateMsg($touser, $url, $template_id, $data)
    {
        return  $this->app->template_message->send([
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'data' => $data
        ]);
    }
}
